<template>
    <el-dialog v-model="AddToOrder" title="Add to Order" width="78%"
        style="position: absolute;top:0px;left:0;right:0; height:69vh;">
        <div class="flex addOrder">
            <div class="flex fdc addLeft brs bs pt-10 pl-10 pr-10 pb-5">
                <p class="f16 fa5">Add items to order</p>
                <div class="flex jc-sb aic mt-10">
                    <el-select v-model="rqfValut" :remote-method="getRfq" remote @change="rfqInfo"
                        @visible-change="visibleRfq" filterable placeholder="Please select an inquiry" style="width: 25%;">
                        <el-option v-for="item in rfqList" :key="item.inquiry_id" :label="item.inquiry_id"
                            :value="item.inquiry_id" />
                    </el-select>
                    <el-button class="add" type="primary" plain @click="add">Add</el-button>
                </div>

                <div class="mt-10">
                    <el-table ref="multipleTableRef" :data="leftList" v-loading="loading" height="50.1vh"
                        style="width: 100%;" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" min-width="30" />
                        <el-table-column property="product.model" label="MODEL" min-width="140" />
                        <el-table-column property="brand.brand_name" label="BRAND" />
                        <el-table-column property="purchaser_id_list" label="BUYER" min-width="100" />
                        <el-table-column property="Qty" label="Qty" min-width="60" />
                        <el-table-column property="item.quotation_price" label="PRICE" min-width="90" />
                        <el-table-column property="item.leadingtime" label="LEADING" min-width="90" />
                        <el-table-column property="item.product_condition" label="CONDITION" min-width="110" />
                    </el-table>
                </div>
            </div>
            <!-- 右边 -->
            <div class="addRight bs brs pl-10 pt-10 pr-10 ">
                <div class="flex jc-sb">
                    <el-select v-model="PI_name" :remote-method="getOrder" remote @change="orderInfo"
                        @visible-change="visibleOrder" filterable :disabled="order" placeholder="Please select the order">
                        <el-option v-for="item in orderList" :key="item.PI_name" :label="item.PI_name"
                            :value="item.order_id" />
                    </el-select>
                    <div>
                        <el-button type="primary" @click="New" plain class="new">New</el-button>
                        <el-button type="primary" @click="save" plain class="new">Save</el-button>
                        <el-popconfirm title="Sure to delete?" @confirm="Delete">
                            <template #reference>
                                <el-button type="primary" class="del" plain>Delete</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </div>
                <div class="mt-10 w100p">
                    <el-table :data="rightList" v-loading="loading" @row-click="row" @selection-change="selectionRightList"
                        height="53.3vh" style="width: 100%">
                        <el-table-column type="selection" min-width="30" />
                        <el-table-column label="MODEL" min-width="180">
                            <template v-slot="model">
                                <el-select v-model="model.row.product_id"
                                    :disabled="model.row.price != '' || !powerList.inquiry.inquiry_model.Isenable"
                                    :remote-method="getModel" remote @change="changeModel" @visible-change="visible"
                                    filterable placeholder="MODEL">
                                    <el-option v-for="item in newModel" :key="item.label" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="BRAND" min-width="120">
                            <template v-slot="brand">
                                <el-select v-model="brand.row.brand_id"
                                    :disabled="brand.row.price != '' || !powerList.inquiry.inquiry_brand.Isenable"
                                    :remote-method="getBrand" remote @visible-change="visible" filterable
                                    placeholder="BRAND">
                                    <el-option v-for="item in newBrand" :key="item.label" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="QTY" min-width="80">
                            <template v-slot="qty">
                                <el-input v-model="qty.row.quantity"
                                    :disabled="qty.row.price != '' || !powerList.inquiry.inquiry_qty.Isenable" />
                            </template>
                        </el-table-column>
                        <el-table-column label="PRICE" min-width="90">
                            <template v-slot="price">
                                <el-input v-model="price.row.price" :disabled="!powerList.inquiry.inquiry_price.Isenable" />
                            </template>
                        </el-table-column>
                        <el-table-column label="LEADING" min-width="125">
                            <template v-slot="leading">
                                <el-select v-model="leading.row.leadingtime" :disabled="!powerList.inquiry.inquiry_leading.Isenable"
                                    filterable placeholder="LEADING">
                                    <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                        :value="item.case" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="CONDITION" min-width="150">
                            <template v-slot="condition">
                                <el-select v-model="condition.row.product_condition"
                                    :disabled="!powerList.inquiry.inquiry_condition.Isenable" filterable placeholder="CONDITION">
                                    <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                        :value="item.case" />
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as $axios from '../../../../api/index'
import useBrand from '../../../../hooks/useBrand'
import useModel from '../../../../hooks/useModel'
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../../../pinia/index'
import usePower from "../../../../hooks/usePower";
const store = useDemoStore()
const { powerList } = usePower()

defineProps({
    newLeading: Array,
    newCondition: Array
})

// 加载
const loading = ref(false)


// 添加订单弹窗
const AddToOrder = ref(false)
const open = () => {
    AddToOrder.value = true
}
// 把open暴露给父组件
defineExpose({
    open
})

const visibleRfq = () => {
    getRfq()
}

// 获取询盘列表
const rqfValut = ref('')
const rfqList = ref([])
const getRfq = (value) => {
    const data = {
        token: store.token,
        keywords: value,
        purchaser: store.type == 3 ? store.userId : '',
    }
    $axios.$orderGet_inquiry_by_key(data).then(res => {
        rfqList.value = res.data.data
        // console.log(rfqList.value)
    })
}


// 获取询盘信息
const leftList = ref([])
const rightList = ref([])
const listArr = ref([])
const srote = ref(false)
const storeValie = ref('')
const PI_name = ref('')
const order_id = ref('')
const rfqInfo = (value) => {
    // console.log(srote.value)
    // 暂时不写
    if (srote.value) {
        rightList.value.forEach(item => {
            if (item.product_name_pi) {
                listArr.value.push({ ...item, state: 1 })  //暂存,填写没保存的
            }
        })
        // rightList.value = listArr.value
    }
    srote.value = false
    // console.log(listArr.value)

    loading.value = true
    storeValie.value = value || storeValie.value
    const data = {
        token: store.token,
        inquiry_id: storeValie.value
    }
    $axios.$orderGet_inquiry_info(data).then(res => {
        loading.value = false
        leftList.value = res.data.inquiryItem   //左边列表数据
        rightList.value = res.data.orderInfo.itemOrder  //右边列表数据
        rightList.value.push({
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "price": ''
        })
        PI_name.value = res.data.orderInfo.PI_name
        order_id.value = res.data.orderInfo.order_id
        order.value = false
        // console.log(rightList.value)
        if (rightList.value.length == 1) { //判断后端有没有数据
            srote.value = true
        }
    })
}

// 左边多选框
const inquiry_item_info_id = ref([])
const handleSelectionChange = (value) => {
    inquiry_item_info_id.value = []
    value.forEach(item => {
        inquiry_item_info_id.value.push(item.item.inquiry_item_info_id)
    });
}

// 添加到右边
const add = () => {
    const data = {
        token: store.token,
        inquiry_item_info_id: inquiry_item_info_id.value
    }
    $axios.$production_item(data).then(res => {
        if (rightList.value.some(item => item.msg == '1')) { //添加到新建的
            rightList.value = []
            rightList.value = [
                ...rightList.value,
                ...res.data
            ]
            rightList.value.push({
                "msg": 1,
                "price": ''
            })

        } else {
            rightList.value.pop()
            rightList.value = [
                ...rightList.value,
                ...res.data
            ]
            rightList.value.push({
                "price": ''
            })
        }
        // console.log(res)
    })
}

// 点击右边表格触发
const row = (data) => {
    // console.log(data)
}

onMounted(() => {
    getModel()
    getBrand()

})

// model
var newModel = ref([])
const getModel = (text) => {
    newModel.value = { newModel } = useModel(text)
}

// brand
var newBrand = ref([])
const getBrand = (text) => {
    newBrand.value = { newBrand } = useBrand(text)
}


// 订单列表选项框打开关闭触发
const visibleOrder = () => {
    getOrder()
}

// 获取订单列表
const orderList = ref([])
const getOrder = (value) => {
    const data = {
        token: store.token,
        keywords: value
    }
    $axios.$orderOrder_listo(data).then(res => {
        orderList.value = res.data.data
        console.log(res.data.data)
    })
}

// 选择订单
const orderInfo = (value) => {
    rightList.value.forEach(item => {
        order_id.value = value
        item.order_id = value
    })
    // console.log(rightList.value)
}


// 右边多选框
const order_info_id = ref([])
const random = ref([])
const selectionRightList = (value) => {
    order_info_id.value = []
    random.value = []
    value.forEach(arr => {
        if (arr.index) {
            random.value.push(arr.index)
        } else {
            // console.log(arr)
            order_info_id.value.push(arr.order_info_id)
        }
    })
    console.log(order_info_id.value)
    console.log(random.value)
}


// 删除
const Delete = () => {
    if (order_info_id.value.length > 0 || random.value.length > 0) {
        if (order_info_id.value && order_info_id.value.length > 0) {
            const data = {
                token: store.token,
                order_id_list: order_info_id.value
            }
            $axios.$orderDel_order(data).then(res => {
                console.log(res)
                order_info_id.value.forEach(item => {
                    const index = rightList.value.findIndex(arr => arr.order_info_id == item)
                    index != -1 && rightList.value.splice(index, 1)  //删除数组里面的成员
                })
                ElMessage({
                    message: 'successfully delete',
                    type: 'success',
                })
            })
        }
        if (random.value.length > 0) {
            random.value.forEach(item => {
                const index = rightList.value.findIndex(arr => arr.index == item)
                index != -1 && rightList.value.splice(index, 1)  //删除数组里面的成员
            })
        }
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }

}


// 新建
const order = ref(false)
const New = () => {
    // console.log(rqfValut.value)
    if (rqfValut.value) {
        rightList.value = []
        PI_name.value = ''
        order.value = true
        for (let i = 0; i < 5; i++) {
            rightList.value.push({
                "msg": 1,
                "price": ''
            })
        }
    } else {
        ElMessage({
            message: 'Please select an inquiry',
            type: 'warning',
        })
    }
}


// 选择最后一个model时创建空白表单
const changeModel = () => {
    const model = rightList.value[rightList.value.length - 1].product_id
    // console.log(model)
    if (model) {
        rightList.value.push({
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "price": ''
        })
    }
}

// 保存
const saveState = ref(true)
const save = () => {
    // console.log(rightList.value)
    const product = ref([])
    const saveData = ref([])
    rightList.value.forEach(data => {
        if (data.product_id) {
            console.log(data)
            if (data.product_id && data.brand_id) {
                saveState.value = true
                saveData.value.push(data)
                product.value = saveData.value.map(item => {
                    return {
                        "order_id": item.order_id || order_id.value,
                        "order_info_id": item.order_info_id ? item.order_info_id : '',
                        "product_id": item.product_id,
                        "brand": item.Brand_name,
                        "brand_id": item.brand_id,
                        "inquiry_id": rqfValut.value,
                        "purchaser_id": item.Purchaser_id ? item.Purchaser_id : '',
                        "inquiry_item_info_id": item.inquiry_item_purchase_price_id ? item.inquiry_item_purchase_price_id : '',
                        "model": item.product_name_pi,
                        "qty": item.quantity || 0,
                        "price": item.price,
                        "leadingtime": item.leadingtime || '',
                        "product_condition": item.product_condition || '',
                    }
                })
            } else {
                saveState.value = false
            }
        }
        // console.log(data)
    })

    // console.log(rightList.value)
    // console.log(saveState.value)
    if (product.value.length != 0 && saveState.value) {
        if (rightList.value.some(item => item.msg == 1)) {  //新增
            const data = {
                token: store.token,
                product: product.value
            }
            $axios.$orderNew_order(data).then(res => {
                if (res.Status === 0) {
                    rfqInfo()
                    order.value = false
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                }
                // console.log(res)
            })
        } else if (!!order_id.value) {  //没有order_id就是没有选择订单，提示选择订单
            const data = {
                token: store.token,
                product: product.value
            }
            $axios.$orderSave_order(data).then(res => {
                if (res.Status === 0) {
                    rfqInfo()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                }
                // console.log(res)
            })
        } else {
            ElMessage({
                message: 'Please select the order',
                type: 'warning',
            })
        }
    } else {
        ElMessage({
            message: 'Please choose model brand',
            type: 'warning',
        })
    }

}

</script>

<style lang="less">
.addRight {
    .el-table .cell {
        padding: 0;
    }

}
</style>

<style lang="less" scoped>
.addOrder {
    width: 100%;

    .brs {
        border-radius: 10px;
    }

    .addLeft {
        width: 47.5%;
    }

    .addRight {
        // padding-left: 10px;
        // margin-left: 10px;
        width: 52.5%;

        .orderDetails:hover .delete {
            visibility: visible;
        }

        .delete {
            visibility: hidden;
        }
    }

    .add.el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: #ecf5ff;
    }

    .el-button.is-plain {
        border: 1px solid #6193D2;
        color: #6193D2;
        background-color: #fff;
    }

    .del.el-button.is-plain {
        border: 1px solid #6193D2;
        color: #fff;
        background-color: #6393D4;
    }

}
</style>